package com.ruoyi.vote.common.messge;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.handler.AllUrlHandler;
import com.ruoyi.mall.enums.OrderInfoEnum;
import com.ruoyi.vote.admin.domain.VoteCertificateReceive;
import com.ruoyi.vote.admin.domain.WxUserSub;
import com.ruoyi.vote.admin.domain.bo.WxUserSubBo;
import com.ruoyi.vote.admin.domain.vo.WxUserSubVo;
import com.ruoyi.vote.admin.service.IWxUserSubService;
import com.ruoyi.vote.common.constants.VoteConstants;
import com.ruoyi.weixin.config.WxMaConfiguration;
import com.ruoyi.weixin.domain.WxUser;
import liquibase.pro.packaged.W;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
public class WeChatMessageHandler {

    /**
     * 发送小程序订阅消息
     * @param wxUsers 用户集合
     * @param templateId 模板ID
     * @param path 发送路径
     * @param wxMaSubMsgList 消息列表
     * @return void
     * @version V1.0
     * modify history
     */
    public static void sendWechatAppSubMessage(List<WxUser> wxUsers,String templateId,String path,ArrayList<WxMaSubscribeMessage.MsgData> wxMaSubMsgList){
        WxMaService maService = WxMaConfiguration.getMaService();
        for (WxUser wxUser : wxUsers) {
            // TODO：根据用户id获取OpenId,测试时写死
            WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
            // 要推送的用户openid
            subscribeMessage.setToUser(wxUser.getOpenId());
            // 订阅消息模板id
            subscribeMessage.setTemplateId(templateId);
            // 跳转小程序地址,没有这填写默认的跳转地址
            String pathUrl = Optional.ofNullable(path).orElse("pages/index/index");
            subscribeMessage.setPage(pathUrl);
            // 消息列表（组装示例请看方法开始注释部分）
            subscribeMessage.setData(wxMaSubMsgList);
            try {
                // 发送订阅消息
                maService.getMsgService().sendSubscribeMsg(subscribeMessage);
            } catch (Exception e) {
                log.error("用户:[ {} ]订阅消息推送失败 - {}" ,wxUser.getOpenId(), e.getMessage());
            }
        }
    }

}
